#encoding=utf8
import os, re, sys
import hashlib, zipfile

apkname="paoniuniu_latest.apk"
chance=1.0000


def mkmd5fromstrc(strc):
    md5 = hashlib.new("md5")
    md5.update(strc)
    return md5.hexdigest()

def mkmd5fromfile(filename):
    fobj = open(filename, "rb")
    md5 = hashlib.new("md5")
    while True:
        fb = fobj.read(1024)
        if not fb:
            break
        md5.update(fb)
    fobj.close()
    return md5.hexdigest()

def main(fout):

    zfile = zipfile.ZipFile(apkname)
    AndroidManifestXml = zfile.read("AndroidManifest.xml")
    zfile.close()
    
    ftemp = file("temp.xml", "wb")
    ftemp.write(AndroidManifestXml)
    ftemp.close()
    os.system("java -jar AXMLPrinter2.jar temp.xml > temp.txt")
    page = file("temp.txt", "rb").read().strip()
    os.system("del temp.xml ")
    os.system("del temp.txt ")
    assert page.endswith("</manifest>"), u"manifest read error..."

    pkg_ver_code = int(re.findall("android:versionCode=\"([0-9]+)\"", page)[0])
    pkg_ver_name = re.findall("android:versionName=\"(.*?)\"", page)[0].strip() # string
    pkg_ver_name = "".join(pkg_ver_name.split())

    def writeln(str):
        fout.write(str)
        fout.write("\r\n")
    writeln("[config.apk.1]")
    writeln("apk.md5=%s" % mkmd5fromfile(apkname))
    writeln("ver.code=%d" % pkg_ver_code)
    writeln("ver.name=%s" % pkg_ver_name)
    writeln("apk.name=%s" % apkname)
    writeln("apk.size=%d" % os.path.getsize(apkname))
    writeln("chance=%d" % int(10000 * chance))
    writeln("")

if __name__ == "__main__":
    fout = file("upgrade.ini", "wb")
    main(fout)
    fout.close()
    print "ok"
    os.system("@Pause")
